

package com.example.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.example.fw.ContactObject;
import com.example.fw.Groups;


public class ContactModificationTests extends TestBase{
Random rnd = new Random();
	
	@DataProvider(name = "randomContacts")
	public Iterator<Object[]> generateRandomContacts() {
		List<Object[]> list = new ArrayList<Object[]>();
		for (int i = 0; i < 1; i++) {
			ContactObject contact = new ContactObject()
			.setFirstname("firstname" + rnd.nextInt())
			.setLastname("lastname" + rnd.nextInt())
			.setAddress("address" + rnd.nextInt())
			.setHometelephone("home" + rnd.nextInt())
			.setMobilelephone("mobile" + rnd.nextInt())
			.setWorktelephone("work" + rnd.nextInt())
			.setEmail(rnd.nextInt() + "e-mail@mail.com")
			.setEmail2(rnd.nextInt() + "e-mail2@mail.com")
			.setBirthday("1")
			.setBirthmonth("February")
			.setBirthyear("1987")
			.setAddress2("address secondary"  + rnd.nextInt())
			.setPhone2("Home secondary" + rnd.nextInt());
			list.add(new Object[]{contact});
		}
	return list.iterator();
	}
	
	@Test(dataProvider = "randomContacts")
	public void testValidContactCanBeModified(ContactObject validContact) throws Exception {
		
		List<ContactObject> oldContactList = app.getHibernateHelper().getContacts();
		app.getContactHelper().modifyContact(0, validContact);

		
		for (ContactObject contact : oldContactList){
			if (contact.id.compareTo(validContact.id) == 0){
				oldContactList.remove(contact);
				//validContact.setFirstname(String.format("%s %s", validContact.firstname, validContact.lastname));
				oldContactList.add(validContact);
				break;
			}
		}
		
		//Set<ContactObject> newContactList = app.getContactHelper().getContacts();
		List<ContactObject> newContactList = app.getHibernateHelper().getContacts();
		//List<ContactObject> newContactList = app.getContactHelper().getContacts();
		assertThat(newContactList, equalTo(oldContactList));
	}
	
	@AfterMethod
	public void testUIConformsWithDB(){
		if (app.getProperty("uiDb.check") != null){
			Groups dbList = app.getHibernateHelper().getGroups();
			Groups uiList = app.getGroupHelper().getUiGroups();
			assertThat(uiList, equalTo(dbList));
		}
		
	}

}
